package com.xbongbong.rule.symbol.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import lombok.extern.slf4j.Slf4j;
import com.xbongbong.rule.rules.XbbCondition;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zheng.li
 **/
@Slf4j
public abstract class AbstractSymbol implements ISymbol {

    protected ConditionEnum conditionEnum;


    protected String attr;

    /**
     * 字段类型
     */
    protected Integer fieldType;
    /**
     * 字段值
     */
    protected Object value;
    /**
     * 条件值
     */
    protected List<Object> conditionValueList = new ArrayList<>();

    protected Object conditionValue;

    protected String conditionValueStr;

    protected static String EMPTY_ARRAY_STR = "[]";

    /**
     * fact
     */
    protected JSONObject factJson;



    @Override
    @SuppressWarnings("unchecked")
     public void parse(XbbCondition item, Object factValue) {
        factJson = (JSONObject) JSONObject.toJSON(factValue);
        if (factJson == null) {
            return;
        }

        conditionEnum = item.getConditionEnum();
        attr = item.getAttr();
        fieldType = item.getFieldType();
        conditionValueStr = item.getValue() != null ? item.getValue().toString() : "";
        // condition中存的都是数组
        List<Object> list;
        if (item.getValue() instanceof  List) {
            list = (List) item.getValue();
        } else {
            list = JSONArray.parseArray(conditionValueStr, Object.class);
        }
        if (CollectionsUtil.isNotEmpty(list)){
            conditionValueList.addAll(list);
        }
        conditionValue = !conditionValueList.isEmpty() ? conditionValueList.get(0): "";
        value = factJson.get(attr);

    }

}
